package com.hanoi.wiki.dao.hibernate;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.UserDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.model.User;

@Component
@Transactional
public class UserDAOHibernate extends HibernateBaseDAO<User, Integer> implements UserDAO{

	public UserDAOHibernate(Class<User> persistenceClass) {
		super(persistenceClass);		
	}
	
	public UserDAOHibernate() {
		super(User.class);
	}
	
	

	@SuppressWarnings("rawtypes")
	@Override
	protected com.hanoi.wiki.dao.hibernate.HibernateBaseDAO.QueryObject buildQueryObject(
			String selectClause, User model) {			
		return null;
	}

	public List<User> getList() throws DataAccessException{
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("SELECT u FROM User u");
		final String queryStr = strBuilder.toString();
		
		@SuppressWarnings("unchecked")
		List<User> results = (List<User>)getJpaTemplate().execute(new JpaCallback<Object>() {
			public Object doInJpa(EntityManager em) throws PersistenceException {
				final Query q = em.createQuery(queryStr);
				return q.getResultList();
			}
		});
		
		return results;
	}
	
	public int saveUser(User user) throws DataAccessException {
		save(user);
		return user.getId();
	}

	public User getUserByName(final String userName) throws DataAccessException {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("SELECT u FROM User u where upper(u.userName) = upper(:userName)");
		final String queryStr = strBuilder.toString();
		
		User result = (User)getJpaTemplate().execute(new JpaCallback<Object>() {
			public Object doInJpa(EntityManager em) throws PersistenceException {
				final Query q = em.createQuery(queryStr);
				q.setParameter("userName", userName);
				return q.getSingleResult();
			}
		});
		
		return result;
	}
	
	
}
